package com.cskaoyan.service;

import com.cskaoyan.bean.MarketRole;
import com.cskaoyan.bean.MarketRoleExample;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.cskaoyan.util.MyBatisUtil;
import com.cskaoyan.util.TransactionUtil;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.*;

/**
 * @author stone
 * @date 2023/03/17 14:24
 */
public class RoleServiceImpl implements RoleService {


    @Override
    public Set<String> queryByIds(Integer[] roleIds) {
        TransactionUtil.startTransaction();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        MarketRoleMapper marketRoleMapper = sqlSession.getMapper(MarketRoleMapper.class);
        Set<String> roles = new HashSet<String>();
        if (roleIds.length == 0) {
            return roles;
        }

        MarketRoleExample example = new MarketRoleExample();
        example.or().andIdIn(Arrays.asList(roleIds)).andEnabledEqualTo(true).andDeletedEqualTo(false);
        List<MarketRole> roleList = marketRoleMapper.selectByExample(example);
        sqlSession.commit();
        for (MarketRole role : roleList) {
            roles.add(role.getName());
        }

        TransactionUtil.commit();
        return roles;
    }

    @Override
    public BaseRespVo list() {
        TransactionUtil.startTransaction();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        MarketRoleMapper marketRoleMapper = sqlSession.getMapper(MarketRoleMapper.class);
        //查询数据
        List<MarketRole> marketRoleList = marketRoleMapper.selectByExample(new MarketRoleExample());

        //构造baseRespVo需要封装的对象
        List<Map<String, Object>> roleVoList = new ArrayList<>();
        for (MarketRole marketRole : marketRoleList) {
            HashMap<String, Object> roleVo = new HashMap<>();
            roleVo.put("label", marketRole.getName());
            roleVo.put("value", marketRole.getId());
            roleVoList.add(roleVo);
        }

        TransactionUtil.commit();
        //返回响应对象
        return BaseRespVo.ok(CommonData.data(new PageInfo(roleVoList)));
    }
}
